<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

/** 侧边栏模型表 */
class SidebarModel extends Model
{
    public $timestamps = false;
    protected $table = 'sidebar';

    /** 列表系統侧边栏 */
    static public function listSystemSidebar()
    {
        $sidebarData = self::where('type', 1)->select('id', 'name', 'level', 'pid', 'url')->orderBy('sort', 'asc')->get()->toArray();
        return self::formatTree($sidebarData, 3);
    }

    /** 列表群组侧边栏 */
    static public function listGroupSidebar($is_admin)
    {
        $type = $is_admin ? [2, 3] : [2];
        $sidebarData = self::whereIn('type', $type)->select('id', 'name', 'level', 'pid', 'url')->orderBy('sort', 'asc')->get()->toArray();
        return self::formatTree($sidebarData, 3);
    }

    /** 生成树结构 */
    static private function formatTree(array $initialData, int $totalLevel)
    {
        $data = [];
        foreach ($initialData as $item) {
            $data[$item['level']][$item['pid']][] = $item;
        }

        if (empty($data)) {
            return json_encode([]);
        }

        ksort($data);
        for ($i = $totalLevel; $i > 1; $i--) {
            foreach ($data[$i - 1] as &$item) {
                foreach ($item as &$subitem) {
                    if (isset($data[$i][$subitem['id']])) {
                        $subitem['items'] = $data[$i][$subitem['id']];
                    }
                }
            }
        }

        return json_encode($data['1']['0']);
    }
}
